import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:xiaofanshu_flutter/controller/story_map_pub_controller.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';

/// 发故事路线的地图页面
/// 与MapPage代码相同，但用于创建故事路线
class StoryRouteMapPage extends StatefulWidget {
  const StoryRouteMapPage({super.key});

  @override
  State<StoryRouteMapPage> createState() => _StoryRouteMapPageState();
}

class _StoryRouteMapPageState extends State<StoryRouteMapPage> {
  final StoryMapPubController controller = Get.find();
  @override
  void initState() {
    super.initState();
    ever(controller.filteredPins, (_) => controller.updateMarkers());
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  // 位置初始化现在由控制器处理，这里删除旧实现

  // 这些方法现在由控制器处理，这里删除旧实现

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() => Stack(
        children: [
          // 高德地图
          AMapWidget(
            privacyStatement: const AMapPrivacyStatement(hasShow: true, hasAgree: true, hasContains: true),
            initialCameraPosition: CameraPosition(
              target: controller.currentLocation.value ?? const LatLng(39.9042, 116.4074),
              zoom: controller.currentZoom.value,
            ),
            markers: Set<Marker>.of(controller.markers),
            polylines: Set<Polyline>.of(controller.routeLines),
            onMapCreated: (mapController) {
              controller.onMapCreated(mapController);
            },
            onCameraMove: (cameraPosition) {
              controller.onCameraMove(cameraPosition);
            },
            onTap: (latLng) {
              // 地图点击事件 - 添加路线marker
              if (controller.isRouteCreationMode.value) {
                controller.addRouteMarker(latLng);
                return; // 在路线创建模式下，不执行其他逻辑
              }
              
              // 关闭弹窗
              if (controller.showFilterPopup.value) {
                controller.toggleFilterPopup();
              }
              if (controller.showStoryPreview.value) {
                controller.closeStoryPreview();
              }
            },
            myLocationStyleOptions: MyLocationStyleOptions(true),
          ),
          
          // 右上角功能按钮
          Positioned(
            top: 60,
            right: 20,
            child: Column(
              children: [
                _buildFilterButton(),
                const SizedBox(height: 15),
                _buildLocationButton(),
                const SizedBox(height: 15),
                _buildZoomInButton(),
                const SizedBox(height: 15),
                _buildZoomOutButton(),
              ],
            ),
          ),
          
          // 筛选弹窗
          if (controller.showFilterPopup.value) _buildFilterPopup(),
          
          // 故事预览弹窗
          if (controller.showStoryPreview.value) _buildStoryPreview(),
          
          // 底部路线创建栏
          if (controller.isRouteCreationMode.value) _buildRouteCreationBar(),
        ],
      )),
    );
  }

  Widget _buildFilterButton() {
    return GestureDetector(
      onTap: controller.toggleFilterPopup,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.filter_list, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildLocationButton() {
    return GestureDetector(
      onTap: controller.moveToCurrentLocation,
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.my_location, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomInButton() {
    return GestureDetector(
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomIn(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.add, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildZoomOutButton() {
    return GestureDetector(
      onTap: () {
        if (controller.mapController != null) {
          controller.mapController?.moveCamera(
            CameraUpdate.zoomOut(),
          );
        }
      },
      child: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: const Icon(Icons.remove, size: 20, color: Colors.grey),
      ),
    );
  }

  Widget _buildFilterPopup() {
    return Obx(() => Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.95),
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, 5),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '选择类别',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
            const SizedBox(height: 10),
            // 添加快速选择按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                TextButton(
                  onPressed: controller.selectAllCategories,
                  child: const Text('全选', style: TextStyle(color: Color(0xFFFF2442))),
                ),
                TextButton(
                  onPressed: controller.clearAllCategories,
                  child: const Text('清空', style: TextStyle(color: Color(0xFF666666))),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: _buildCategoryTags(),
            ),
            const SizedBox(height: 20),
            Row(
              children: [
                const Text('官方认证'),
                const Spacer(),
                Switch(
                  value: controller.showOfficialOnly.value,
                  onChanged: (value) => controller.toggleOfficialOnly(),
                  activeColor: const Color(0xFFFF2442),
                ),
              ],
            ),
            const SizedBox(height: 20),
            // 用户筛选
            TextField(
              decoration: InputDecoration(
                hintText: '输入用户昵称进行筛选',
                prefixIcon: const Icon(Icons.person_search, color: Color(0xFF999999)),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFFCCD5)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: const BorderSide(color: Color(0xFFFF2442)),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              ),
              onChanged: (value) => controller.nicknameFilter.value = value,
            ),
            const SizedBox(height: 20),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: controller.confirmFilterAndReload,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFFF2442),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                ),
                child: const Text('确认', style: TextStyle(color: Colors.white)),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  List<Widget> _buildCategoryTags() {
    if (controller.categories.isEmpty) {
      return const [Center(child: Text('加载分类中...'))];
    }

    return controller.categories.map((category) {
      String categoryName = category['categoryName'] ?? '未知分类';
      String categoryKey = categoryName.toLowerCase();
      bool isSelected = controller.selectedCategories[categoryKey] ?? false;
      
      return GestureDetector(
        onTap: () => controller.toggleCategory(categoryKey),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFF0F5),
            border: Border.all(
              color: isSelected ? const Color(0xFFFF2442) : const Color(0xFFFFCCD5),
            ),
            borderRadius: BorderRadius.circular(15),
          ),
          child: Text(
            categoryName,
            style: TextStyle(
              color: isSelected ? Colors.white : const Color(0xFFFF2442),
              fontSize: 12,
            ),
          ),
        ),
      );
    }).toList();
  }

  Widget _buildStoryPreview() {
    return Obx(() {
      if (controller.filteredPins.isEmpty) return const SizedBox.shrink();
      
      // 确保当前索引在有效范围内
      if (controller.currentStoryIndex.value >= controller.filteredPins.length) {
        controller.currentStoryIndex.value = 0;
      }
      if (controller.currentStoryIndex.value < 0) {
        controller.currentStoryIndex.value = 0;
      }
      
      final currentStory = controller.filteredPins[controller.currentStoryIndex.value];
      
      return Positioned(
        bottom: 20,
        left: 20,
        right: 20,
        child: GestureDetector(
          onTap: () => controller.navigateToStoryDetail(currentStory),
          child: Container(
            padding: const EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 5),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  currentStory.title,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF333333),
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  currentStory.content,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF666666),
                  ),
                ),
                const SizedBox(height: 10),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () => controller.navigateToUserProfile(currentStory.authorId ?? ''),
                      child: CircleAvatar(
                        radius: 15,
                        backgroundColor: const Color(0xFFFFF0F5),
                        backgroundImage: currentStory.authorAvatar != null 
                            ? NetworkImage(currentStory.authorAvatar!) 
                            : null,
                        child: currentStory.authorAvatar == null 
                            ? const Icon(Icons.person, size: 12, color: Colors.grey)
                            : null,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      currentStory.author,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    IconButton(
                      icon: const Icon(Icons.arrow_back_ios, size: 16),
                      onPressed: controller.previousStory,
                    ),
                    IconButton(
                      icon: const Icon(Icons.arrow_forward_ios, size: 16),
                      onPressed: controller.nextStory,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget _buildRouteCreationBar() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, -5),
            ),
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 模式切换和状态显示
            Row(
              children: [
                Expanded(
                  child: Obx(() => Text(
                    controller.isStoryConnectionMode.value
                        ? '故事连接模式：点击故事marker进行连接'
                        : '地点添加模式：点击地图添加地点',
                    style: TextStyle(
                      fontSize: 14,
                      color: controller.isStoryConnectionMode.value 
                          ? Colors.green 
                          : Colors.grey,
                      fontWeight: controller.isStoryConnectionMode.value 
                          ? FontWeight.bold 
                          : FontWeight.normal,
                    ),
                  )),
                ),
                Obx(() => ElevatedButton(
                  onPressed: controller.toggleStoryConnectionMode,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: controller.isStoryConnectionMode.value
                        ? Colors.orange
                        : Colors.green,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                  child: Text(
                    controller.isStoryConnectionMode.value ? '退出连接' : '连接故事',
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                  ),
                )),
              ],
            ),
            const SizedBox(height: 12),
            
            // 路线名称输入
            Row(
              children: [
                Expanded(
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: '请输入路线名称',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(color: CustomColor.primaryColor),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    ),
                    onChanged: (value) => controller.routeName.value = value,
                  ),
                ),
                const SizedBox(width: 12),
                Obx(() => ElevatedButton(
                  onPressed: controller.isStoryConnectionMode.value
                      ? controller.saveStoryRoute
                      : controller.confirmRouteCreation,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: CustomColor.primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                  ),
                  child: Text(
                    controller.isStoryConnectionMode.value ? '保存' : '确认',
                    style: const TextStyle(color: Colors.white),
                  ),
                )),
              ],
            ),
            const SizedBox(height: 12),
            
            // 状态信息和操作按钮
            Row(
              children: [
                Obx(() => Text(
                  controller.isStoryConnectionMode.value
                      ? '已连接故事: ${controller.connectedStoryPins.length}/${controller.maxConnectedStories}'
                      : '已添加地点: ${controller.routeMarkers.length}/${controller.maxMarkers}',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                )),
                const Spacer(),
                Obx(() => controller.connectedStoryPins.isNotEmpty
                    ? TextButton(
                        onPressed: controller.clearAllConnectedStories,
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.orange,
                        ),
                        child: const Text('清空连接'),
                      )
                    : const SizedBox.shrink()),
                Obx(() => !controller.isStoryConnectionMode.value
                    ? TextButton(
                        onPressed: controller.clearAllRouteMarkers,
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.red,
                        ),
                        child: const Text('清空选择'),
                      )
                    : const SizedBox.shrink()),
              ],
            ),
          ],
        ),
      ),
    );
  }
}